package com.easycarebn.main.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.service.request.OnRequest;
import com.timbacsi.main.R;

public class FragmentForgetPass extends Fragment {

	private View mView;
	private static FragmentForgetPass fragment = null;
	private IResult callIResult;
	private static String mTitle;
	private EditText edPhone;
	private EditText edCode;
	private LinearLayout line_nhap_sdt;
	private LinearLayout line_nhap_code;

	Button btnSendPhone;
	Button btnActive;

	private String mPhone = "";
	private ProgressBar mLoadding;
	private TextView btnNhanlai;

	public static FragmentForgetPass newInstance(String title) {

		fragment = new FragmentForgetPass();
		mTitle = title;
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IResult) {
			callIResult = (IResult) activity;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_forgetpass, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		callIResult.onDisplay(Utils.TASK_CHILD, "");
		Utils.setTitlePage(mView, mTitle);
		Utils.setOnTouchHideKeyboard(getActivity(), (ViewGroup) mView);
		edPhone = (EditText) mView.findViewById(R.id.edPhone);
		edCode = (EditText) mView.findViewById(R.id.edCode);
		edCode.setText("");
		line_nhap_sdt = (LinearLayout) mView.findViewById(R.id.line_nhap_sdt);
		line_nhap_code = (LinearLayout) mView.findViewById(R.id.line_nhap_code);
		line_nhap_code.setVisibility(View.GONE);
		line_nhap_sdt.setVisibility(View.VISIBLE);

		mLoadding = (ProgressBar) mView.findViewById(R.id.loadding);

		btnNhanlai = (TextView) mView.findViewById(R.id.btnNhanlaima);
		btnSendPhone = (Button) mView.findViewById(R.id.btnLogin);
		btnSendPhone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getCodeActive();
			}
		});

		Button	btnLoginForm = (Button) mView.findViewById(R.id.btnLoginForm);
		btnLoginForm.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//Utils.intentToDetailt(getActivity(), Utils.LOGIN);
				callIResult.onDisplay(Utils.LOGIN, getResources().getString(R.string.lblDangnhap));
			}
		});
		
		
		btnActive = (Button) mView.findViewById(R.id.btnActive);
		btnActive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				activeCode();
			}
		});

		btnNhanlai.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				resendCode();
			}
		});
	}

	public void resendCode() {

		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, (ViewGroup) mView);
		ServerController.getInstance(getActivity()).requestsendResetCode(
				mPhone, 1, new OnRequest<DataItemResponse>() {

					@Override
					public void onSuccess(DataItemResponse data) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
						if (data.getCode() == StatusCode.OK) {
							Utils.showMessage(
									getActivity(),
									getResources().getString(
											R.string.nhan_lai_maxt_thanhcong));
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.showMessage(getActivity(), message);
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
					}
				});

	}

	private void activeCode() {
		Log.d("seRsetCode", "seRsetCode");
		String resetCode = edCode.getText().toString();
		if (TextUtils.isEmpty(resetCode)) {
			Utils.showMessage(getActivity(), R.string.nhap_ma_xac_thuc_pass);
			return;
		}

		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, (ViewGroup) mView);

		ServerController.getInstance(getActivity()).requestdoResetPass(mPhone,
				resetCode, new OnRequest<DataItemResponse>() {

					@Override
					public void onSuccess(DataItemResponse data) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
						if (data == null) {
							return;
						}
						if (data.getCode() == StatusCode.OK) {
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.kiem_tra_email));
						} else {
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.ma_xt_khong_hop_le));

						}

					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
						Utils.showMessage(getActivity(), message);
					}
				});

	}

	private void getCodeActive() {
		mPhone = edPhone.getText().toString();
		if (mPhone.isEmpty()) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.vui_long_nhap_so_dt));
			return;
		}

		if (mPhone.length() < 10 || mPhone.length() > 11) {
			Utils.showMessage(getActivity(),
					getResources().getString(R.string.so_dien_thoai_ko_hop_le));
			return;
		}

		mLoadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, (ViewGroup) mView);

		ServerController.getInstance(getActivity()).requestsendResetCode(
				mPhone, 0, new OnRequest<DataItemResponse>() {

					@Override
					public void onSuccess(DataItemResponse data) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
						if (data == null) {
							return;
						}
						if (data.getCode() == StatusCode.OK) {
							line_nhap_code.setVisibility(View.VISIBLE);
							line_nhap_sdt.setVisibility(View.GONE);
							Utils.showMessage(getActivity(), getResources()
									.getString(R.string.vui_long_doi_tn));

						} else {
							Utils.showMessage(
									getActivity(),
									getResources().getString(
											R.string.khong_tim_thay_nguoi_dung));
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						mLoadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, (ViewGroup) mView);
						Utils.showMessage(getActivity(), message);
					}
				});

	}

	public BroadcastReceiver mybroadcast = new TextMessageReceiver();

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(mybroadcast);
		super.onPause();
	}

	@Override
	public void onResume() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		getActivity().registerReceiver(mybroadcast, filter);
		super.onResume();
	}

	public class TextMessageReceiver extends BroadcastReceiver {

		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();

			Object[] messages = (Object[]) bundle.get("pdus");
			SmsMessage[] sms = new SmsMessage[messages.length];

			for (int n = 0; n < messages.length; n++) {
				sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
			}

			try {
				for (SmsMessage msg : sms) {

					String arrays[] = msg.getMessageBody().split(" ");
					String s = arrays[arrays.length - 1].toString().trim();
					if (!s.isEmpty()
							&& msg.getMessageBody().contains("Easycare")) {
						if (s.length() == 5) {
							edCode.setText(s);
							// activeCode();
						} else if (s.length() == 6) {
							Utils.showMessage(getActivity(), "Đăng nhập");
							mLoadding.setVisibility(View.VISIBLE);
							Utils.requestLogin(getActivity(), callIResult,
									mPhone, s, false);
							// callIResult.onDisplay(Utils.SHOW_HOME,
							// getResources().getString(R.string.lblDangnhap));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
